package com.mymvc.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mymvc.from.ActionForm;
import com.mymvc.from.FullForm;
import com.mymvc.from.XmlBean;


public class ActionService extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 700296676723369227L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
				//获取请求头
				String path = this.getPath(request.getServletPath());
				Map<String,XmlBean> map = (Map<String,XmlBean>) this.getServletContext().getAttribute("my-mvc-xml.xml");
				XmlBean xml = map.get(path);
				String beanclass = xml.getBeanclass();
				ActionForm form = FullForm.full(beanclass, request);
				String actionClass = xml.getType();
				Action action = null;
				String url = "";
				try
				{
					Class clazz = Class.forName(actionClass);
					action 		= (Action) clazz.newInstance();
					url = action.execute(request, response, form, xml.getResultMap());
				}catch (Exception e) {
					e.printStackTrace();
				}
//				//获得了转发器对象
				RequestDispatcher dis = request.getRequestDispatcher(url);
				dis.forward(request, response);		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	private String getPath(String servletpath)
	{
		return servletpath.split("\\.")[0];
	}

}
